package com.gillion.grape.fros.ui.commands;

import java.io.InputStream;

import net.java.amateras.uml.model.RootModel;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.ui.IFileEditorInput;

import com.gillion.grape.fros.ui.Entity2ERUtils;



/**
 * 实体模型转PSM
 * @author meichenhui
 * @since 2011-8-29
 *
 */
public abstract class EntityPIM2PSM implements IModelTransform {

	/**
	 * 实体模型文件
	 */
	private IFileEditorInput umlModelFileInput;
	/**
	 * 工程路径
	 */
	private String projectPath;
	
	private RootModel rootModel;
	
	/**
	 * 当前编辑的模型文件所属的模块
	 */
	private String moduleName;
	
	public String getModuleName() {
		return moduleName;
	}

	public void setModuleName(String moduleName) {
		this.moduleName = moduleName;
	}

	protected String getProjectPath(){
		return projectPath;
	}
	
	protected IFileEditorInput getUMLModelFileInput(){
		return umlModelFileInput;
	}
	
	@Override
	public void setUnTransformModel(Object unTransformModel) {
		this.umlModelFileInput = (IFileEditorInput)unTransformModel;
	}

	@Override
	public void setTransformedArguments(Object args) {
		projectPath = (String)args;
	}

	/**
	 * 得到从模型文件反序列化出来的UML模型
	 * @return
	 *
	 * @author meichenhui
	 * @since 2011-8-24
	 *
	 */
	protected RootModel getRootModel(){
		if (rootModel == null){
			rootModel = Entity2ERUtils.deserializUMLDiagram(getUMLModelFileInput()); // UML图形反序列化为图形对象
		}
		return rootModel;
	}
	
	@Override
	public void serializeTransformedModel(String label) {
		RootModel diagramObject = getRootModel();
		if (diagramObject.getChildren().size() == 0){ // 空图形不做操作
			return;
		}
		InputStream erSerializedStream = genTransformedModelFileContentStream(); // 生成代码
		if (erSerializedStream == null){
			return;
		}
		writeFile(erSerializedStream,getTargetFile());
	}
	
	/**
	 * 模型转换后要写入的文件
	 * @return
	 *
	 * @author meichenhui
	 * @since 2011-8-24
	 *
	 */
	protected abstract IFile getTargetFile();
	
	/**
	 * 写入文件
	 * @param content
	 *
	 * @author meichenhui
	 * @since 2011-8-24
	 *
	 */
	private void writeFile(InputStream content,IFile targetFile){
		// 代码写入文件
		try {
			if (targetFile.exists()){
				targetFile.setContents(content, IFile.FORCE, new NullProgressMonitor());
			} else {
				targetFile.create(content, false, null);
			}
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 转换后模型要写入文件的流
	 * @return
	 *
	 * @author meichenhui
	 * @since 2011-8-24
	 *
	 */
	protected abstract InputStream genTransformedModelFileContentStream();

}